<template>
  <div>
    <div class="list-card-operation">
      <t-button @click="formDialogVisible = true"> {{ $t('pages.listCard.create') }} </t-button>
      <div class="search-input" style="display: flex">
        <t-button theme="primary" @click="toAll"> 全部 </t-button>
        <t-button variant="outline" theme="primary" @click="toItem"> 商品 </t-button>
        <t-button variant="outline" theme="primary" style="margin-right: 7px" @click="toService"> 服务 </t-button>
        <t-input
          v-model="searchValue"
          :placeholder="$t('pages.listCard.placeholder')"
          clearable
          @keypress="handleSearch"
        >
          <template #suffix-icon>
            <search-icon v-if="searchValue === ''" size="var(--td-comp-size-xxxs)" />
          </template>
        </t-input>
      </div>
    </div>

    <dialog-form v-model:visible="formDialogVisible" :data="formData" />
    <edit-form v-model:visible="formDialogVisible01" :data="editData" />

    <template v-if="pagination.total > 0 && !dataLoading">
      <div class="list-card-items">
        <t-row :gutter="[16, 16]">
          <t-col
            v-for="product in productList.slice(
              pagination.pageSize * (pagination.current - 1),
              pagination.pageSize * pagination.current,
            )"
            :key="product.index"
            :lg="4"
            :xs="6"
            :xl="3"
          >
            <product-card
              class="list-card-item"
              :product="product"
              @delete-item="handleDeleteItem"
              @manage-product="handleManageProduct"
            />
          </t-col>
        </t-row>
      </div>
      <div class="list-card-pagination">
        <t-pagination
          v-model="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-size-options="[12, 24, 36]"
          @page-size-change="onPageSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </template>

    <div v-else-if="dataLoading" class="list-card-loading">
      <t-loading size="large" text="加载数据中..." />
    </div>

    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除所选商品？"
      :body="confirmBody"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<script lang="ts">
export default {
  name: 'GoodsManage',
};
</script>

<script setup lang="ts">
import axios from 'axios';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import { deleteGoods, getGoodsList, getItemList, getServiceList } from '@/api/list';
import type { CardProductType } from '@/components/default-card/index.vue';
import ProductCard from '@/components/default-card/index.vue';

import type { FormData } from './components/DialogForm.vue';
import DialogForm from './components/DialogForm.vue';
import EditForm from './components/EditForm .vue';

const INITIAL_DATA: CardProductType = {
  id: 0,
  name: '',
  describe: '',
  price: null,
  img: '',
  rest: 0,
  isOnShelf: false,
  type: 'item',
};

const pagination = ref({ current: 1, pageSize: 12, total: 0 });
const deleteProduct = ref<CardProductType | undefined>(undefined);

const productList = ref([]);
const dataLoading = ref(true);

const fetchData = async () => {
  try {
    const response = await axios.get('/api/admin/getGoods');
    const { list } = response.data.data;
    console.log(list);
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const confirmBody = computed(() =>
  deleteProduct.value ? `确认删除后${deleteProduct.value.name}的所有商品信息将被清空, 且无法恢复` : '',
);

onMounted(() => {
  fetchData();
});

const formDialogVisible = ref(false);
const formDialogVisible01 = ref(false);
const searchValue = ref('');
const confirmVisible = ref(false);
const formData = ref({ ...INITIAL_DATA });
const editData = ref({ ...INITIAL_DATA });

let timeout = null;
const handleSearch = () => {
  if (searchValue.value === '') {
    // 当用户清空搜索框时，这里发送请求
    fetchData();
    return;
  }
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    // 当用户停止输入后，这里发送请求
    fetchSearchResults(searchValue.value);
  }, 300); // 300毫秒防抖时间
};

const fetchSearchResults = async (query: string) => {
  try {
    const response = await axios.get('/api/admin/getGoods', {
      params: { name: query },
    });
    // 处理响应数据
    console.log(response.data);
    const { list } = response.data.data;
    if (list === null) {
      productList.value = [];
      pagination.value = {
        ...pagination.value,
        total: 0,
      };
      return;
    }
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (error) {
    console.error('Error fetching search results:', error);
  } finally {
    dataLoading.value = false;
  }
};

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
};
const handleDeleteItem = (product: CardProductType) => {
  confirmVisible.value = true;
  deleteProduct.value = product;
};
const onConfirmDelete = async () => {
  console.log(deleteProduct.value.id);
  console.log(deleteProduct.value.type);
  const deleteResponse = await axios.delete('/api/admin/deleteItem', {
    data: {
      id: deleteProduct.value.id,
    },
  });
  confirmVisible.value = false;
  await MessagePlugin.success('删除成功');
  await fetchData();
};
const onCancel = () => {
  deleteProduct.value = undefined;
  formData.value = { ...INITIAL_DATA };
};
const handleManageProduct = async (product: CardProductType) => {
  formDialogVisible01.value = true;
  if (product.type === 'item') {
    const rest = await axios.get('/api/user/getRest', {
      params: {
        id: product.id,
      },
    });
    editData.value = {
      id: product.id,
      name: product.name,
      describe: product.describe,
      price: product.price,
      img: product.img,
      rest: rest.data.data.rest,
      isOnShelf: product.isOnShelf,
      type: product.type,
    };
  } else {
    editData.value = {
      id: product.id,
      name: product.name,
      describe: product.describe,
      price: product.price,
      img: product.img,
      rest: undefined,
      isOnShelf: product.isOnShelf,
      type: product.type,
    };
  }
  console.log(editData.value);
};
const toAll = async () => {
  try {
    const response = await axios.get('/api/admin/getGoods');

    // 从返回的响应中提取数据
    const { list } = response.data.data;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const toItem = async () => {
  try {
    const response = await axios.get('/api/admin/getAllItem');

    // 从返回的响应中提取数据
    const { list } = response.data.data;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const toService = async () => {
  try {
    const response = await axios.get('/api/admin/getAllService');

    // 从返回的响应中提取数据
    const { list } = response.data.data;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
.list-card {
  height: 100%;

  &-operation {
    display: flex;
    justify-content: space-between;
    margin-bottom: var(--td-comp-margin-xxl);

    .search-input {
      width: 500px;
    }
  }

  &-item {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);

    :deep(.t-card__header) {
      padding: 0;
    }

    :deep(.t-card__body) {
      padding: 0;
      margin-top: var(--td-comp-margin-xxl);
      margin-bottom: var(--td-comp-margin-xxl);
    }

    :deep(.t-card__footer) {
      padding: 0;
    }
  }

  &-pagination {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);
  }

  &-loading {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
